package web

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"log"
)

type Helper struct {
	EngIne     *gin.Engine
	DB         *gorm.DB
	Controller *Controller
}

func CreateWebHelper(db *gorm.DB) *Helper {
	gin.SetMode(gin.DebugMode)
	engine := gin.Default()
	engine.Use(cors.Default())
	store := cookie.NewStore([]byte("secret"))
	engine.Use(sessions.Sessions("ota-session", store))
	controller := CreateController(*db)
	webHelper := &Helper{
		EngIne:     engine,
		DB:         db,
		Controller: controller,
	}
	return webHelper
}

func (h *Helper) Run() {
	err := h.EngIne.Run(":8080")
	if err != nil {
		log.Fatalln("启动失败:", err)
		return
	}
}

func (h *Helper) RegisterInterfaces() {
	var api Api = h.Controller
	h.EngIne.POST("/login", api.Login)
	h.EngIne.GET("/getUserInfo", api.GetUserInfo)
	h.EngIne.POST("/logout", api.Logout)
	h.EngIne.POST("/updateUserInfo", api.UpdateUserInfo)
	h.EngIne.POST("/submitOtaUpdate", api.SubmitOtaUpdateInfo)
	h.EngIne.POST("/getOtaUpdateInfos", api.GetOtaUpdateInfos)
	h.EngIne.POST("/getOtaUpdateInfo", api.GetOtaUpdateInfo)
	h.EngIne.POST("/deleteOtaUpdateInfo", api.DeleteOtaUpdateInfo)
	h.EngIne.POST("/checkOtaUpdate", api.CheckOtaUpdate)
	h.EngIne.POST("/uploadFile", api.UploadFile)
	h.EngIne.GET("/getAllUploadFiles", api.GetAllUploadFiles)
}
